<template>
  <a-select 
    :style="placeObj"
    showSearch
    allowClear
    :disabled="disabled"
    :filterOption="filterOption"
    :placeholder="placeholder"
    @change="handleChange"
    :value="seletedValue"
  >
    <a-select-option v-if="dictCategoryOpt" value="dictCategory" key="dictCategory">
      {{ showCode ? 'dictCategory--字典分类' : '字典分类' }}
    </a-select-option>
    <a-select-option
      v-for="(item, dictCode) in dictOptions"
      :key="dictCode"
      :value="item.dictCode">
      {{ showCode ? item.dictCode + '--' + item.dictEntry : item.dictEntry }}
      <!-- {{ item.dictCode }}-{{ item.dictEntry }} -->
    </a-select-option>
  </a-select>
</template>

<script>
import { getDictByCategory } from './dict'

export default {
  name: 'dictSelect',
  props: {
    dictCategory: {
      required: true,
      type: String
    },
    disabled:{
      type: Boolean
    },
    placeholder: {
      default: '',
      required: false,
      type: String
    },
    dictCategoryOpt: {
      default: false,
      required: false,
      type: Boolean
    },
    showCode: {
      default: false,
      required: false,
      type: Boolean
    },
    all: {
      default: false,
      required: false,
      type: Boolean
    },
    value: {
      default: '',
      required: false,
      type: String 
    }
  },
  data () {
    return {
      dictOptions: [],
      seletedValue:  (this.value == '' || this.value === null) ? undefined : this.value
    }
  },
  computed:{
    placeObj(){
      if(this.value==''){
        return {color:'#bbb' }
      }
    }
  },
  created () {
    this.initDictData()
  },
  methods: {
    initDictData () {
      if (this.dictCategory === '字典分类') {
        this.dictCategory = 'dictCategory'
      }
      const parameter = {
        dictCategory: this.dictCategory
      }
      getDictByCategory(parameter, {}).then(r => {
        if (r && r && r.code === 'C1' && r.data) {
          this.dictOptions = r.data
        }
        if (this.all) {
          const tn = {
            dictCode: 'all',
            dictEntry: '全部'
          }
          this.dictOptions.unshift(tn)
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      )
    },
    handleChange (val) {
      this.$emit('change', val)
      // this.$emit('dataChanged', val)
    }
  },
  watch: {
    value: function () {
      this.seletedValue = (this.value == '' || this.value === null) ? undefined : this.value
    }
  }
}
</script>
<style  scoped>
</style>
